package eu.codlab.androidemu;

import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import eu.codlab.androidemu.gbcdroid.FileChooserAdapter;
import eu.codlab.androidemu.gbcdroid.ListListener;
import eu.codlab.androidemu.origbc.FileSelectedListener;
import eu.codlab.androidemu.utilities.ZipRead;
import eu.codlab.src.game.R;

import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
/**
 * Class representing helper functions for the default screen
 * where the user can select files and folders
 * 
 * @author codlab
 *
 */
public class ActivitiesHelper 
implements ListListener, FileFilter, View.OnKeyListener, IActivitiesHelper{
	protected Activity _activity;
	protected FileSelectedListener _file_selected_listener;

	protected View click = null;

	protected final File sdcardDir = Environment.getExternalStorageDirectory();
	protected File currentDir;
	protected String[] filters;
	protected EditText pathEdit;
	private File save = null;
	public ActivitiesHelper(){

	}
	public ActivitiesHelper(Activity activity, FileSelectedListener file_selected_listener, String path){

		_activity = activity;
		_file_selected_listener=file_selected_listener;

		filters = getFileFilter();
		File dir = null;
		if (path != null)
			dir = getDirectoryFromFile(path);
		if (dir == null)
			dir = sdcardDir;
		changeTo(dir);

	}

	public void setClickView(View v){
		click = v;
		pathEdit = (EditText)click.findViewById(R.id.path);
		pathEdit.setOnKeyListener(this);

		changeTo(save);
	}

	public String[] getFileFilter() {
		return _activity.getResources().getStringArray(R.array.file_chooser_filters);
	}
	public void refresh(){
		changeTo(currentDir);
	}

	public void sdcard(){
		changeTo(this.sdcardDir);
	}

	public void parent(){
		if(currentDir != null){
			File parent = currentDir.getParentFile();
			if (parent != null)
				changeTo(parent);
		}
	}


	//ListManagement
	public void onListItemClick(String name, View v, int position, long id) {
		File f = currentDir;
		if("..".equals(name)){
			if(f.getParentFile() != null)
				f = f.getParentFile();
		}else
			f = new File(currentDir, name);


		if(f.isDirectory())
			changeTo(f);
		else
			_file_selected_listener.onFileSelected(Uri.fromFile(f));
	}
	public void onSaveInstanceState(Bundle outState) {
		if (currentDir != null)
			outState.putString("currentDir", currentDir.getAbsolutePath());
	}	

	public boolean accept(File file) {
		String name = file.getName();

		// Do not show hidden files
		if (name.startsWith("."))
			return false;

		// Always show directory
		if (file.isDirectory())
			return true;

		name = name.toLowerCase();
		/*if(name.endsWith(".zip")){
			ZipRead zipread = new ZipRead();
			zipread.compute(file);
			return zipread.isGBA() || zipread.isGBC();
		}*/
		for (String f : filters) {
			if (name.endsWith(f))
				return true;
		}
		return false;
	}

	public File getDirectoryFromFile(String path) {
		File _dir = new File(path);
		if (!_dir.isDirectory()) {
			_dir.getParentFile();
			if (_dir != null && !_dir.isDirectory())
				_dir = null;
		}
		return _dir;
	}



	public void changeTo(File dir) {
		if(click == null){
			save = dir;
			return;
		}
		if(dir == null)
			return;
		Log.d("changing to save", dir.getAbsolutePath());
		ListView _l = (ListView)click.findViewById(R.id.liste);
		if(_l != null){
			File[] files = dir.listFiles(filters == null ? null : this);
			if (files == null)
				files = new File[0];

			currentDir = dir;
			if(pathEdit != null)
				pathEdit.setText(dir.getAbsolutePath());

			List<String> items = new ArrayList<String>(files.length);
			for (File f : files) {
				String name = f.getName();
				if (f.isDirectory())
					name += '/';
				items.add(name);
			}

			Collections.sort(items, String.CASE_INSENSITIVE_ORDER);
			if(!"/".equals(currentDir))
				items.add(0, "..");
			_l.setAdapter(new FileChooserAdapter(_activity, this, (ArrayList<String>) items,currentDir));
			save = currentDir;
		}else if(save == null){
			save = currentDir;
		}
	}


	@Override
	public boolean onKey(View v, int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_ENTER) {
			String name = pathEdit.getText().toString().trim();
			if (name.length() > 0) {
				File _dir = new File(name);
				if (_dir.isDirectory() && click != null)
					changeTo(_dir);
				else {
					_activity.runOnUiThread(new Thread(){
						public void run(){
							Toast.makeText(_activity, R.string.invalid_dir,
									Toast.LENGTH_SHORT).show();
						}
					});
				}
				return true;
			}
		}
		return false;
	}


}
